;
(function($) {
	"use strict";

	var commonLayer,
			salesPromotion,
			$cartGoodList = $("#cartGoodList"),
			$checkbox = $cartGoodList.find(".checkbox"),
			$sortCheckbox = $cartGoodList.find(".all_choose .checkbox"),
			$allCheck = $(".shp-chk .checkbox"),
			$itemList = $cartGoodList.find("li"),
			$allPrice = $(".shp-cart-info .money"),
			$allJifen = $(".shp-cart-info .jifen");
	commonLayer = {
		init :function(){

			var str = '<ul class="layerlist">'+
					'<li><img src="http://dummyimage.com/136x136/000/fff"><span class="title">Estee Lauder雅诗Estee Lauder雅诗Estee Lauder雅诗Estee Lauder雅诗</span></li>'+
					'</ul>';
			ECar.mModal.confirm({
				height:470,
				title: "以下商品已售完！",
				maskAlpha: "1",
				content: str
			});

		}
	};

	$(".checkbox").click(function(){
		var $self = $(this),
				$itemList = $self.closest("ul").find("li"),
				$price = $itemList.find(".money"),
				$jiFen = $itemList.find(".jifen");
		if($self.hasClass("active")){
			$self.removeClass("active");
		}else{
			$self.addClass("active");
		}
		countAll();
		return false;
	});
	$sortCheckbox.click(function(){
		var $self = $(this),
				$thisform =  $(this).closest(".cart_list_box").find(".checkbox");
		if($self.hasClass("active")){
			$thisform.addClass("active");
		}else{
			$thisform.removeClass("active");
		}
		countAll();
		return false;
	})
	$allCheck.click(function(){
		var $self = $(this);
		if($self.hasClass("active")){
			$(".checkbox").attr("class","checkbox active");
		}else{
			$(".checkbox").attr("class","checkbox");
		}
		countAll();
		return false;
	})

	$cartGoodList.find("ul .sales_promotion_box").click(function(){
		var $self = $(this),
				$ico =	$self.find(".promotion_ico"),
				$txt =  $self.find(".promotion_list");
		if($ico.hasClass("promotion_ico_open")){
			$ico.removeClass("promotion_ico_open");
			$txt.css("height",".8rem");
		}else{
			$ico.addClass("promotion_ico_open");
			$txt.css("height","auto");
		}
		return false;
	})

	commonLayer.init();

//返回顶部
    $(window).on("scroll",function(){
			if( $(window).scrollTop() > 200 ){
				$("#gotopbtn").show(); 	
			}else{ 	
				$("#gotopbtn").hide();
			}	
		}); 	
   (function(){ 	
   	  var btn = document.getElementById("gotopbtn");	 	
	  var timer = null; 	
	  var isTop = true;

	  //获取页面可视区高度 	
	  var clientHeight = document.documentElement.clientHeight;

	  //滚动条滚动时触发 	
	  btn.onclick = function() {

	    //设置定时器 	
	    timer = setInterval(function(){
 	
	      //获取滚动条距离顶部高度 	
	      var osTop = document.documentElement.scrollTop || document.body.scrollTop; 	
	      var ispeed = Math.floor(-osTop / 7); 	
	      document.documentElement.scrollTop = document.body.scrollTop = osTop+ispeed;
 	 	
	      //到达顶部，清除定时器 	
	      if (osTop == 0) { 	
	        clearInterval(timer); 	
	      }; 	
	      isTop = true; 	
	    },30); 	
	  };
 	
   })();

// 选择地区
	$(".icon_address, .order_address").tap(function() {
		var that = $(".order_address");
		ECar.mSelect.show({
			provinceUrl: "/resources/data/province.json",
			cityUrl: "/resources/data/city.json",
			regionUrl: "/resources/data/region.json",
			data: that.data("address"),
			closeFn: function() {
				var address = ECar.mSelect.result;
				if (address.code === "") return;

				that.focus().val(address.province.name + address.city.name + address.region.name)
						.data("address", JSON.stringify(address)).blur();
			}
		});
	});
//编辑
	$itemList.find(".edit").click(function(){
		var $self = $(this),
				//$thislist = $self.closest("ul").find("li").not(".merger_payment"),
				$thislist = $self.closest("li"),
				$title = $thislist.find(".title"),
				$btn_number = $thislist.find(".btn_number"),
				$del = $thislist.find(".del"),
				$finish = $thislist.find(".finish");

		$title.hide();
		$btn_number.show().css("display","inline-block");
		$del.hide();
		$self.hide();
		$finish.show();
		return false;
	})
//完成
	$itemList.find(".finish").click(function(){
		var  $self = $(this),
				//$thislist = $self.closest("ul").find("li").not(".merger_payment"),
				$thislist = $self.closest("li"),
				$title = $thislist.find(".title"),
				$btn_number = $thislist.find(".btn_number"),
				$del = $thislist.find(".del"),
				$edit = $thislist.find(".edit"),
				numberVal =$thislist.find(".good_number").val(),
				$number = $thislist.find(".number span");
		$title.show();
		$btn_number.hide();
		$edit.show();
		$del.show();
		$self.hide();
		$number.html(numberVal);
		countAll();
		return false;
	})
	var countAll = function(obj){
		//obj.price obj.jifen obj.isAdd
		var allPrice = 0,
				allJifen = 0,
				price,
				jifen,
				datalength;
		if(length > 1){
			datalength = obj.price.length -1;
		}else{
			datalength = 1;
		}
		var $selected = $("#cartGoodList .checkbox_box .active"),
				datalength = $selected.length;

		for(var i = 0; i< datalength ; i++ ){
			var $content = $selected.eq(i).closest(".checkbox_box").siblings(".list_content");
			var $price = $content.find(".money"),
					$jifen = $content.find(".jifen"),
					$number = $content.find(".number span");
			price = ($price.html() ? parseFloat($price.html()) :0)* $number.html();
			jifen = ($jifen.html() ? parseFloat($jifen.html()) :0)* $number.html();
			allPrice +=  price;
			allJifen +=  jifen;

			/*	if(obj.isAdd){
			 allPrice +=  price;
			 allJifen +=  jifen;
			 }else{
			 allPrice -=  price;
			 allJifen -=  jifen;
			 }*/
		}
		$allPrice.html(allPrice);
		$allJifen.html(allJifen);
	}
	countAll();



	var setNumber = function(value,type,obj,btn,stock){
		var value = parseInt(value)<1?1:parseInt(value);
		switch (type) {
			case "reduce":
				if (value > 1) {
					value = value - 1;
				}
				break;
			case "add":
				if (value < stock) {
					value = value + 1;
				}
				break;
			case "input":
				value = value >= stock?stock:value;
		}
		obj.val(value);
		return value;
	}

	var setBtnStyle = function(type,value,stock,self) {
		if(stock <= value){
			//$('.btn_'+type).addClass('disabled');
			self.find('.btn_'+type).addClass('disabled');
		}
		if(stock > value){
			//$('.btn_number span').removeClass('disabled');
			self.find("span").removeClass('disabled');
		}
		if(value==1 && type == "reduce"){
			//$('.btn_'+type).addClass('disabled');
			self.find('.btn_'+type).addClass('disabled');
		}
	}

	var getSkuAjax = function(){
		return $.ajax({
			url:"/resources/js/skuAjax.js",
			async:false
		});
	}

	var handleSkuNum = function(count) {
		var nFlag = this.validSkuNum(count);
		if (nFlag === 0) {

			return count.replace("0", "");
		} else if (nFlag === -1) {
			return 1;
		} else {
			return count;
		}
	}

	// 校验商品数量是否符合规则
	var validSkuNum = function(count) {
		if(count=='')return 2;
		if (/^[1-9][0-9]?$/.test(count)) {
			return 1;
		} else if (/^0[1-9]$/.test(count)) {
			return 0;
		} else {
			return -1;
		}
	}


	var good_number = $('.good_number');

	$('.btn_number span.btn_reduce,.btn_number span.btn_add').on('click',function(e){
		var $this = $(this),
				inputObj =$this.siblings('.good_number'),
				type = $this.data('btn-type'),
				value = inputObj.val(),
				boxObj = $this.closest("li");
		if($this.hasClass('disabled')) return false;
		var stock = $.parseJSON(getSkuAjax().response);
		var newValue = setNumber(value,type,inputObj,$this,stock.skuStock);
		setBtnStyle(type,newValue,stock.skuStock,boxObj);
		return false;
	});
	function onlyNum() {
		if(!(event.keyCode==46)&&!(event.keyCode==8)&&!(event.keyCode==37)&&!(event.keyCode==39))
			if(!((event.keyCode>=48&&event.keyCode<=57)||(event.keyCode>=96&&event.keyCode<=105)))
				event.returnValue=false;
	}
	good_number.on('keyup',function(e){
		var sKeyCode = e.which || e.keyCode,
				sCount = $(this).val(),
				nFlag = validSkuNum(sCount);
		if ((sKeyCode >= 96 && sKeyCode <= 105) || (sKeyCode >= 48 && sKeyCode <= 57)) {
			return;
		}
		switch (nFlag) {
			case 0:
				sCount = 1;
				break;
			case -1:
				sCount = 1;
				break;
			default:
				return;
		}

		$(this).val(sCount);
	});

	good_number.on("change", function() {
		var sCount = $(this).val(),
				nFlag = validSkuNum(sCount);
		switch (nFlag) {
			case 0:
				sCount = 1;
				break;
			case -1,2:
				sCount = 1;
				break;
			default:
				var stock = $.parseJSON(getSkuAjax().response);
					alert(222)
				var newValue = setNumber(sCount,'input',$(this),$(this),stock.skuStock);
				return;
		}
		$(this).val(sCount);
	});


})(Zepto, window.ECar || (window.ECar = {}));